Interactive JavaScript DOM Manipulation

1. HTML and CSS Manipulation

Change Text Content (innerHTML)


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <div>
        <button onclick="changeText()">Change Text</button>
        <div id="textElement" class="output-box">Original Text</div>
    </div>
    <Script>
        function changeText() {
            document.getElementById('textElement').innerHTML = 'Updated Text Content!';
        }
    </Script>
</body>
</html>
            
Original Text

Change Style (CSS)


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <div>
        <button class="btn btn-info mb-2" onclick="changeStyle()">Change Style</button>
        <div  id="styledElement" class="output-box">Original Styled Element</div>
    </div>
    <Script>
        function changeStyle() {
            document.getElementById('styledElement').style.color = 'blue';
            document.getElementById('styledElement').style.fontSize = '24px';
            document.getElementById('styledElement').style.fontWeight = 'bold';
        }
    </Script>
</body>
</html>
            
Original Styled Element

Add/Remove Elements


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <div>
        <button class="btn btn-success mb-2" onclick="addElement()">Add Element</button>
        <button class="btn btn-danger mb-2" onclick="removeElement()">Remove Element</button>
        <div  id="elementContainer" class="output-box">
            <p id="removableElement">This element can be removed.</p>
        </div>
    </div>
    <Script>
        // Add Element
        function addElement() {
            var newElement = document.createElement('p');
            newElement.innerText = 'This is a newly added paragraph.';
            document.getElementById('elementContainer').appendChild(newElement);
        }
        // Remove Element
        function removeElement() {
            var element = document.getElementById('removableElement');
            if (element) {
                element.remove();
            }
        }
    </Script>
</body>
</html>
            

This element can be removed.

Event Listener Example


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <div>
        <button id="eventButton" class="btn btn-warning mb-2">Click Me</button>
    </div>
    <Script>
        document.getElementById('eventButton').addEventListener('click', function() {
            alert('Button clicked!');
        });
    </Script>
</body>
</html>